package org.ricks.gateway.ws;

import org.ricks.net.action.ActionBus;
import org.ricks.net.action.context.DefHeadMeta;
import org.ricks.net.action.context.FlowContext;
import org.ricks.net.action.context.session.WebSocketSessionAdapter;
import org.ricks.net.action.parser.ProtocolParserEnum;
import org.ricks.net.http.codec.CloseReason;
import org.ricks.net.http.server.WebSocketRequest;
import org.ricks.net.http.server.WebSocketResponse;
import org.ricks.net.http.server.handler.WebSocketDefaultHandler;

import java.nio.ByteBuffer;

public class WSHandler extends WebSocketDefaultHandler {


    @Override
    public void handleTextMessage(WebSocketRequest request, WebSocketResponse response, String data) {
        response.ping("hello".getBytes());
        response.sendTextMessage("接受到客户端消息：" + data);
    }

    @Override
    public void handleBinaryMessage(WebSocketRequest request, WebSocketResponse response, byte[] data) {
        ByteBuffer byteBuffer = ByteBuffer.wrap(data);
        short cmd = byteBuffer.getShort();
        byte[] bytes = new byte[byteBuffer.remaining()];
        byteBuffer.get(bytes);
        ActionBus.handlerAction(request.hashCode(), new FlowContext<>(new WebSocketSessionAdapter(response),
                new DefHeadMeta(cmd),bytes,
                ProtocolParserEnum.PROTOBUF.getParser()));
    }

    @Override
    public void onClose(WebSocketRequest request, WebSocketResponse response, CloseReason closeReason) {
        System.out.println("客户端关闭连接，状态码：" + closeReason.getCode());
        System.out.println("客户端关闭连接，原因：" + closeReason.getReason());
        super.onClose(request, response, closeReason);
    }
}
